/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.edu.thu.laud.utils;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.cassandra.auth.IAuthenticator;
import org.apache.cassandra.thrift.AuthenticationException;
import org.apache.cassandra.thrift.AuthenticationRequest;
import org.apache.cassandra.thrift.AuthorizationException;
import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Cassandra.Client;
import org.apache.cassandra.thrift.CfDef;
import org.apache.cassandra.thrift.ColumnDef;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.KsDef;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.cassandra.thrift.SchemaDisagreementException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.datanucleus.ClassLoaderResolver;
import org.datanucleus.exceptions.NucleusDataStoreException;
import org.datanucleus.metadata.AbstractClassMetaData;
import org.datanucleus.metadata.AbstractMemberMetaData;
import org.datanucleus.metadata.ColumnMetaData;
import org.datanucleus.metadata.EmbeddedMetaData;
import org.datanucleus.metadata.Relation;
import cn.edu.thu.laud.objectstore.CassandraConnectionInfo;
import cn.edu.thu.laud.objectstore.CassandraStoreManager;
import cn.edu.thu.laud.objectstore.index.CompositeUtil;

/**
 * 
 * @author zhuoan
 *
 */
public class CassandraUtils {

    /**
     * Accessor for the default value specified for the provided member.
     * If no defaultValue is provided on the column then returns null.
     * @param mmd Metadata for the member
     * @return The default value
     */
    public static String getDefaultValueForMember(AbstractMemberMetaData mmd)
    {
        ColumnMetaData[] colmds = mmd.getColumnMetaData();
        if (colmds == null || colmds.length < 1)
        {
            return null;
        }
        return colmds[0].getDefaultValue();
    }
    
    /**
     * Accessor for the Cassandra qualifier name for the field of this embedded field. 
     * Extracts the qualifier name using the following priorities
     * <ul>
     * <li>If column is specified as "a:b" then takes "b" as the qualifier name.</li>
     * <li>Otherwise takes the column name as the qualifier name when it is specified</li>
     * <li>Otherwise takes "VERSION" as the qualifier name</li>
     * </ul>
     * @param mmd Metadata for the owning member
     * @param fieldNumber Member number of the embedded object
     * @return The qualifier name
     */
    public static String getQualifierName(AbstractMemberMetaData mmd, int fieldNumber)
    {
        String columnName = null;

        // Try the first column if specified
        EmbeddedMetaData embmd = mmd.getEmbeddedMetaData();
        AbstractMemberMetaData embMmd = null;
        if (embmd != null)
        {
            AbstractMemberMetaData[] embmmds = embmd.getMemberMetaData();
            embMmd = embmmds[fieldNumber];
        }

        ColumnMetaData[] colmds = embMmd.getColumnMetaData();
        if (colmds != null && colmds.length > 0)
        {
            columnName = colmds[0].getName();
        }
        if (columnName == null)
        {
            // Fallback to the field/property name
            columnName = embMmd.getName();
        }
        if (columnName.indexOf(":") > -1) {
			columnName = columnName.substring(columnName.indexOf(":") + 1);
		}
		return columnName;
    }

    
    public static String getQualifierName(AbstractClassMetaData acmd,
            int absoluteFieldNumber) {
    	
		AbstractMemberMetaData ammd = acmd
		.getMetaDataForManagedMemberAtAbsolutePosition(absoluteFieldNumber);
		String columnName = null;
		
		// Try the first column if specified
		ColumnMetaData[] colmds = ammd.getColumnMetaData();
		if (colmds != null && colmds.length > 0) {
			columnName = colmds[0].getName();
		}
		if (columnName == null) {
			// Fallback to the field/property name
			columnName = ammd.getName();
		}
		if (columnName.indexOf(":") > -1) {
			columnName = columnName.substring(columnName.indexOf(":") + 1);
		}
		return columnName;
    }
    
    /**
     * Accessor for the Cassandra family name for the field of the embedded field. 
     * Extracts the family name using the following priorities
     * <ul>
     * <li>If column is specified as "a:b" then takes "a" as the family name.</li>
     * <li>Otherwise takes table name as the family name</li>
     * </ul>
     * @param mmd Metadata for the embedded field
     * @param fieldNumber Number of the field in the embedded object
     * @return The family name
     */
    public static String getFamilyName(AbstractMemberMetaData mmd, int fieldNumber, String defaultName)
    {
        // Try from the column name if specified as "a:b"
        EmbeddedMetaData embmd = mmd.getEmbeddedMetaData();
        AbstractMemberMetaData embMmd = null;
        if (embmd != null)
        {
            AbstractMemberMetaData[] embmmds = embmd.getMemberMetaData();
            embMmd = embmmds[fieldNumber];
            ColumnMetaData[] colmds = embMmd.getColumnMetaData();
            if (colmds != null && colmds.length > 0)
            {
            	String colName = colmds[0].getName();
            	if (colName != null && colName.indexOf(":") > 0)
                {
                    return colName.substring(0, colName.indexOf(":"));
                }            	
            }
        }

        // Fallback to table name
        return defaultName;
    }

    public static String getFamilyName(AbstractClassMetaData acmd, int absoluteFieldNumber, String defaultName) {
    	
    	AbstractMemberMetaData ammd = acmd.getMetaDataForManagedMemberAtAbsolutePosition(absoluteFieldNumber);
        String columnName = null;

        // Try the first column if specified
        ColumnMetaData[] colmds = ammd.getColumnMetaData();
        if (colmds != null && colmds.length > 0)
        {
            columnName = colmds[0].getName();
            if (columnName != null && columnName.indexOf(":")>-1)
            {
                return columnName.substring(0,columnName.indexOf(":"));
            }
        }
        
        // Fallback to table name
    	return defaultName;
    }
    
    public static void createSchema(CassandraConnectionInfo connectionInfo){
    	
        Client client = getConnection(connectionInfo);
        String keyspace = connectionInfo.getKeyspace();

        if (client == null) {
            throw new NucleusDataStoreException(
                    "No connection to the data store");
        }	
        KsDef ks = null;
        try {
			ks = client.describe_keyspace(keyspace);
			client.set_keyspace(keyspace);
			if(getCf(ks, keyspace+"_index") == null){
				CfDef cfIndex = new CfDef(keyspace, keyspace+"_index")
				.setComparator_type(
						"DynamicCompositeType"
								+ CompositeUtil.DEFAULT_DYNAMIC_COMPOSITE_ALIASES)
				.setKey_cache_size(0).setRow_cache_size(0)
				.setKey_validation_class("UTF8Type");
				client.system_add_column_family(cfIndex);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			
			if(getCf(ks, keyspace+"_index_entries") == null){
				CfDef cfIndexEntries = new CfDef(keyspace, keyspace+"_index_entries")
				.setComparator_type(
						"DynamicCompositeType"
								+ CompositeUtil.DEFAULT_DYNAMIC_COMPOSITE_ALIASES)
				.setKey_cache_size(0).setRow_cache_size(0);
				client.system_add_column_family(cfIndexEntries);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "CDS") == null){
				CfDef cf_def = new CfDef(ks.getName(), "CDS")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "DBS") == null){
				CfDef cf_def = new CfDef(ks.getName(), "DBS")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "DB_PRIVS") == null){
				CfDef cf_def = new CfDef(ks.getName(), "DB_PRIVS")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "FIELDS") == null){
				CfDef cf_def = new CfDef(ks.getName(), "FIELDS")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "GLOBAL_PRIVS") == null){
				CfDef cf_def = new CfDef(ks.getName(), "GLOBAL_PRIVS")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "IDXS") == null){
				CfDef cf_def = new CfDef(ks.getName(), "IDXS")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "SORT_ORDER") == null){
				CfDef cf_def = new CfDef(ks.getName(), "SORT_ORDER")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "PARTITIONS") == null){
				CfDef cf_def = new CfDef(ks.getName(), "PARTITIONS")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "PART_COL_PRIVS") == null){
				CfDef cf_def = new CfDef(ks.getName(), "PART_COL_PRIVS")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "PARTITION_EVENTS") == null){
				CfDef cf_def = new CfDef(ks.getName(), "PARTITION_EVENTS")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "PART_PRIVS") == null){
				CfDef cf_def = new CfDef(ks.getName(), "PART_PRIVS")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "ROLES") == null){
				CfDef cf_def = new CfDef(ks.getName(), "ROLES")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "ROLE_MAP") == null){
				CfDef cf_def = new CfDef(ks.getName(), "ROLE_MAP")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "SERDES") == null){
				CfDef cf_def = new CfDef(ks.getName(), "SERDES")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "SDS") == null){
				CfDef cf_def = new CfDef(ks.getName(), "SDS")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "TBLS") == null){
				CfDef cf_def = new CfDef(ks.getName(), "TBLS")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "TBL_COL_PRIVS") == null){
				CfDef cf_def = new CfDef(ks.getName(), "TBL_COL_PRIVS")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "TBL_PRIVS") == null){
				CfDef cf_def = new CfDef(ks.getName(), "TBL_PRIVS")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			if(getCf(ks, "TYPES") == null){
				CfDef cf_def = new CfDef(ks.getName(), "TYPES")
				.setComparator_type("BytesType");
				client.system_add_column_family(cf_def);
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			}
			
		
			
		} catch (NotFoundException e) {
			// TODO Auto-generated catch block	
			List<CfDef> cfList = new ArrayList<CfDef>();
			CfDef cfIndex = new CfDef(keyspace, keyspace+"_index")
			.setComparator_type(
					"DynamicCompositeType"
							+ CompositeUtil.DEFAULT_DYNAMIC_COMPOSITE_ALIASES)
			.setKey_cache_size(0).setRow_cache_size(0)
			.setKey_validation_class("UTF8Type");
			cfList.add(cfIndex);
			
			CfDef cfIndexEntries = new CfDef(keyspace, keyspace+"_index_entries")
			.setComparator_type(
					"DynamicCompositeType"
							+ CompositeUtil.DEFAULT_DYNAMIC_COMPOSITE_ALIASES)
			.setKey_cache_size(0).setRow_cache_size(0);
			cfList.add(cfIndexEntries);
			
			CfDef cf_def = new CfDef(keyspace, "CDS")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "DBS")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "DB_PRIVS")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "FIELDS")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "GLOBAL_PRIVS")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "IDXS")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "SORT_ORDER")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "PARTITIONS")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "PART_COL_PRIVS")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "PARTITION_EVENTS")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "PART_PRIVS")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "ROLES")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "ROLE_MAP")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "SERDES")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "SDS")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "TBLS")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "TBL_COL_PRIVS")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "TBL_PRIVS")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			cf_def = new CfDef(keyspace, "TYPES")
				.setComparator_type("BytesType");
			cfList.add(cf_def);
			
			ks = new KsDef(keyspace,
					"org.apache.cassandra.locator.SimpleStrategy", cfList);
			Map<String, String> replicationStrategyOptions = new HashMap<String, String>();
			replicationStrategyOptions.put("replication_factor", String.valueOf(connectionInfo.getReplication()));
			ks.setStrategy_options(replicationStrategyOptions);
			try {
				client.system_add_keyspace(ks);
								
				try {
					Thread.sleep(connectionInfo.getCheckSleepTime());
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
				}
			} catch (InvalidRequestException ex) {
				// TODO Auto-generated catch block
				throw new NucleusDataStoreException(ex.getMessage(), ex);
			} catch (SchemaDisagreementException ex) {
				// TODO Auto-generated catch block
				throw new NucleusDataStoreException(ex.getMessage(), ex);
			} catch (TException ex) {
				// TODO Auto-generated catch block
				throw new NucleusDataStoreException(ex.getMessage(), ex);
			}
			
		} catch (InvalidRequestException e) {
			// TODO Auto-generated catch block
			 throw new NucleusDataStoreException(e.getMessage(), e);
		}  catch (SchemaDisagreementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  catch (TException e) {
			// TODO Auto-generated catch block
			 throw new NucleusDataStoreException(e.getMessage(), e);
		}
    
    }
    
   
    /**
     * Generates the elements in fault within the schema, when running the application
     */
    public static void createSchema(AbstractClassMetaData acmd,
                                    CassandraStoreManager storeMgr) throws IOException {

       
    	if (acmd.isEmbeddedOnly())
        {
             // No schema required since only ever embedded
             return;
        }
        CassandraConnectionInfo connectionInfo = storeMgr
                .getConnectionInfo();
        Client cassandraClient = getConnection(connectionInfo);
        String keyspace = connectionInfo.getKeyspace();

        if (cassandraClient == null) {
            throw new NucleusDataStoreException(
                    "No connection to the data store");
        }
       
        String cfName = acmd.getTable();
        if(cfName == null)
        	cfName = acmd.getName();        
        
        try {
        	
        	KsDef ks = cassandraClient.describe_keyspace(keyspace);        	
            if (getCf(ks, cfName) != null) {
            	CfDef cf_def = new CfDef(keyspace, cfName)
				.setComparator_type("BytesType");
            	cassandraClient.system_add_column_family(cf_def);
            }
            
            int[] fieldNumbers =  acmd.getAllMemberPositions();
            ClassLoaderResolver clr = storeMgr.getOMFContext().getClassLoaderResolver(null);
            for(int i=0; i<fieldNumbers.length; i++)
            {
                AbstractMemberMetaData mmd = acmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumbers[i]);
                int relationType = mmd.getRelationType(clr);
                if ((relationType == Relation.ONE_TO_ONE_UNI || relationType == Relation.ONE_TO_ONE_BI) && mmd.isEmbedded())
                {
                    createSchemaForEmbeddedMember(cassandraClient, ks, keyspace, cfName, mmd, clr);
                }
                else
                {
                    String familyName = getFamilyName(acmd, fieldNumbers[i], cfName);
                    //create ...
                    if(getCf(ks, familyName) != null){
	                    CfDef cf_def = new CfDef(keyspace, familyName)
	    				.setComparator_type("BytesType");
	                	cassandraClient.system_add_column_family(cf_def);
                    }
                }
            }

            
        } catch (NotFoundException e) {
            throw new NucleusDataStoreException(e.getMessage(), e);
        } catch (TException e) {
            throw new NucleusDataStoreException(e.getMessage(), e);
        } catch (InvalidRequestException e) {
			// TODO Auto-generated catch block
        	throw new NucleusDataStoreException(e.getMessage(), e);
		} catch (SchemaDisagreementException e) {
			// TODO Auto-generated catch block
			throw new NucleusDataStoreException(e.getMessage(), e);
		}
        
    }
    
    private static boolean createSchemaForEmbeddedMember(Cassandra.Client cassandraClient, KsDef ks, String keyspace, 
            String cfName, AbstractMemberMetaData mmd, ClassLoaderResolver clr) throws InvalidRequestException, SchemaDisagreementException, TException
    {
        EmbeddedMetaData embmd = mmd.getEmbeddedMetaData();
        AbstractMemberMetaData[] embmmds = embmd.getMemberMetaData();
        for (int j=0; j<embmmds.length; j++)
        {
            AbstractMemberMetaData embMmd = embmmds[j];
            int embRelationType = embMmd.getRelationType(clr);
            if ((embRelationType == Relation.ONE_TO_ONE_UNI || embRelationType == Relation.ONE_TO_ONE_BI) && embMmd.isEmbedded())
            {
                // Recurse
                return createSchemaForEmbeddedMember(cassandraClient, ks, keyspace, cfName, embMmd, clr);
            }
            else
            {
                String familyName = getFamilyName(embMmd, j, cfName);
                if(getCf(ks, familyName) != null){
	                CfDef cf_def = new CfDef(keyspace, cfName)
					.setComparator_type("BytesType");
	            	cassandraClient.system_add_column_family(cf_def);
                }
            }
        }

        return true;
    }
    
    public static CfDef getCf(KsDef keyspace, String cfName)
    {
        if(!keyspace.isSetCf_defs())
        	return null;
    	for (CfDef cfDef : keyspace.cf_defs) {
            if (cfDef.name.equals(cfName))
                return cfDef;
        }

        return null;
    }
    
    /**
	 * Returns true if the column exists, false otherwise
	 * 
	 * @param cfName
	 * @param cf
	 * @return
	 */
	public static boolean hasColumn(CfDef cf, ByteBuffer colName) {
		
		if (!cf.isSetColumn_metadata()) {
			return false;
		}

		for (ColumnDef col : cf.getColumn_metadata()) {
			if (colName.equals(col.name)) {
				return true;
			}
		}

		return false;
	}
    

	/**
	 * Get the column family and return it.  Creating it if required
	 * @param cfName
	 * @return
	 */
	public static boolean createCf(Cassandra.Client client, KsDef keyspace, String cfName) {
	
		CfDef columnFamily = getCf(keyspace, cfName);
		
		// no column family, define one
		if (columnFamily == null) {
			
			try {
				CfDef cf_def = new CfDef(keyspace.getName(), cfName)
				.setComparator_type("BytesType");
	        	client.system_add_column_family(cf_def);
			} catch (Exception e) {
				e.printStackTrace();
				throw new NucleusDataStoreException(String.format("Unable to add column family %s", cfName));
			}
			
			return true;
		}

		return false;
	}

    public static Client getConnection(CassandraConnectionInfo connectionInfo) {
    	
        Map<String, Integer> connections = connectionInfo.getConnections();
        Iterator<String> connections_iterator = connections.keySet().iterator();

        boolean connection = false;
        Client cassandraClient = null;

        while (connections_iterator.hasNext() && !connection) {
            String host = (String) connections_iterator.next();
            connection = true;
            TSocket socket = new TSocket(host, connections.get(host));
            TTransport transport = new TFramedTransport(socket);
            TProtocol protocol = new TBinaryProtocol(transport);
            cassandraClient = new Client(protocol);
            Map<String, String> credentials = new HashMap<String, String>();
            //TODO 不能用root root登陆啊 root将来会被禁止登陆的
            credentials.put(IAuthenticator.USERNAME_KEY, "testadmin");
            credentials.put(IAuthenticator.PASSWORD_KEY, "test");
            try {
                transport.open();
                cassandraClient.login(new AuthenticationRequest(credentials));
            } catch (TTransportException e) {
                System.out.println("Dead client: " + host + ":"
                        + connections.get(host));
                connection = false;
            } catch (AuthenticationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (AuthorizationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (TException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

        }

        return cassandraClient;
    }

 }
